package org.ucas.kgraph.utils.security;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.ucas.kgraph.entity.Account;
import org.ucas.kgraph.entity.Role;
import org.ucas.kgraph.service.PermService;
import org.ucas.kgraph.service.UserService;
import org.ucas.kgraph.utils.common.EncodeUtil;

import java.util.List;

import javax.annotation.PostConstruct;

public class ShiroDbRealm extends AuthorizingRealm {

  @Autowired
  protected UserService userService;
  @Autowired
  protected PermService permService;

  /**
   * 授权检查回调函数,进行鉴权但缓存中无用户的授权信息时调用
   * @param principals
   * @return
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    UserPrincipal principal = (UserPrincipal) principals.getPrimaryPrincipal();
    Account account = userService.load(principal.id).get();
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    
    info.setRoles(account.getRolesName());
    //System.out.println("=+=++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+account.getRolesName().toString());
    //用户的角色对应的所有权限，如果只使用角色定义访问权限，下面的四行可以不要
    List<Role> roleList=account.getRoleList();
    for (Role role : roleList) {
    	info.addStringPermissions(role.getPermsName());
    }
    return info;
  }

  /**
   * 认证回调函数,验证身份时使用
   * @param authcToken
   * @return
   * @throws AuthenticationException
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    Account account = userService.findByName(token.getUsername()).orElse(null);
    if (account!=null) {
      if (account.isDisabled()) {
        throw new DisabledAccountException();
      }
      byte[] salt = EncodeUtil.decodeHex(account.getSalt());
      SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
    		   new UserPrincipal(account.getId()),
    		   account.getPassword(),
               ByteSource.Util.bytes(salt),
               getName());;
      return authenticationInfo;
    } else {
    	throw new UnknownAccountException();//没找到帐号  
      
    }
  }

  /**
   * 设定Password校验的Hash算法与迭代次数.
   */
  @PostConstruct
  public void initCredentialsMatcher() {
    HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserService.HASH_ALGORITHM);
    matcher.setHashIterations(UserService.HASH_INTERATIONS);

    setCredentialsMatcher(matcher);
  }

}
